//
//  FileCacheDefaults.swift
//  ZLKit_Swift
//
//  Created by iOS on 2022/8/5.
//

open class FileCacheDefaults {
    
    public enum FileType: String {
        /// 图片
        case image = "Image"
        /// 视频
        case video = "Video"
    }
    
    public enum ImageFileType: String {
        /// 原始图
        case origin = "Origin"
        /// 按照传入的尺寸
        case frame = "Frame"
    }
    
    /// 重置缓存器，存储的文件会被删除
    static public func resetFileCache(fileType: FileType, quality: ImageFileType? = nil) {
        var path = cacheDirectory + "/\(rootDirectoryName)"
        path = path + "/\(fileType.rawValue)"
        if let quality = quality {
            path = path + "/\(quality.rawValue)"
        }
        guard FileManager.default.fileExists(atPath: path) else { return }
        try? FileManager.default.removeItem(atPath: path)
    }
    
    /// 沙盒目录
    static private let cacheDirectory = (NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]).first ?? ""
    
    /// 沙盒目录
    static private var rootDirectoryName: String = {
        let infoDictionary = Bundle.main.infoDictionary ?? [:]
        let displayName = infoDictionary ["CFBundleDisplayName"] as? String ?? ""
        return displayName.hashHex(by: .MD5).capitalized
    }()
        
    /// 获取文件沙盒路径
    public class func getSandboxUrl(remoteUrl: String, fileType: FileType, quality: ImageFileType) -> URL {
        let remoteUrl = remoteUrl.URLChineseDecoding()
        let name = remoteUrl.hashHex(by: .MD5).lowercased() + (fileType == .video ? ".mp4" : ".png")
        let qualityStr = quality.rawValue
        let fileTypeStr = fileType.rawValue
        let directoryPath = cacheDirectory + "/\(rootDirectoryName)" + "/\(fileTypeStr)" + "/\(qualityStr)"
        if !FileManager.default.fileExists(atPath: directoryPath) {
            try? FileManager.default.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil)
        }
        let filePath = directoryPath + "/\(name)"
//        print("filePath = \(filePath)")
        return .init(fileURLWithPath: filePath)
    }
    
    /// 是否存在
    public class func isExist(remoteUrl: String, fileType: FileType, quality: ImageFileType) -> Bool {
        let fileSandboxUrl = getSandboxUrl(remoteUrl: remoteUrl, fileType: fileType, quality: quality)
        let isPathExists = FileManager.default.fileExists(atPath: fileSandboxUrl.path)
        let isAbsoluteStringExists = FileManager.default.fileExists(atPath: fileSandboxUrl.absoluteString)
        let results = isPathExists || isAbsoluteStringExists
        return results
    }
    
}

